# 导入蓝图包
import os
from flask import Blueprint,request,jsonify
import json

import flask
from requests.api import get

from data import get_data

# 创建蓝图
bp_course = Blueprint('course',__name__)
# 封装的方法
from db import db1

# 接口
@bp_course.route('/couponM',methods=['POST','GET','PUT','DELETE'])
def couponM():
    # 获取数据
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        # 构造SQL语句
        sql = """insert into coupon values(0,'%s','%d','%s','%s')"""%(data['name'],int(data['total']),data['starttime'],data['endtime'])
        # db添加
        db1.intsert(sql)
        # 返回结果
        return '添加成功'

    # 获取
    elif request.method == 'GET':
        # 根据id获取出数据
        id = request.args.get('id')
        sql = """select * from coupon where id=%d"""%(int(id))
        res = db1.find(sql)
        return jsonify({'code':200,'coupon':res})

    # 修改
    elif request.method == 'PUT':
        # 获取用户输入的数据
        data = request.data
        if  data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        # 构造sql语句  update 表名 set 字段名1=值,字段名2=值 where id=1
        sql = """update coupon set name='%s',total=%d,starttime='%s',endtime='%s' where id=%d"""%(data['name'],int(data['total']),data['starttime'],data['endtime'],int(data['id']))
        print(sql)
        db1.intsert(sql)
        return jsonify({'code':200})

    # 删除
    elif request.method == 'DELETE':
        # 获取id
        id = request.args.get('id')
        print(id)
        # 删除获取到的id的数据
        sql = "delete from coupon where id=%d"%(int(id))
        print(sql)
        # 删除方法
        db1.intsert(sql)
        return jsonify({'code':200})

# section部门表
@bp_course.route('/section',methods=['POST','GET','PUT','DELETE'])
def section():
    if request.method == 'POST':
        # 获取传过来的数据
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        # 构造sql 语句
        sql = """insert into section values(0,"%s",%d)"""%(data['name'],int(data['sum']))
        print(sql)
        # db添加
        db1.intsert(sql)
        # 返回结果
        return jsonify({'code':200})

    # 获取数据
    elif request.method == 'GET':
        data = request.form
        sql = """select * from section"""
        res = db1.fingall(sql)
        return jsonify({'code':200,'sections':res})

    # 修改
    elif request.method == 'PUT':
                # 获取用户输入的数据
        data = request.data
        if  data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        # 构造sql语句  update 表名 set 字段名1=值,字段名2=值 where id=1
        sql = """update section set name="%s",sum=%d where id=%d"""%(data['name'],int(data['sum']),int(data['id']))
        print(sql)
        db1.intsert(sql)
        return jsonify({'code':200})

 
    # 删除数据
    elif request.method == 'DELETE':
        id = request.args.get('id')
        sql = """delete from staff where id=%d"""%(int(id))
        db1.intsert(sql)
        return jsonify({'code':200})

# staff员工表
@bp_course.route('/staff',methods=['POST','GET','PUT','DELETE'])
def staff():
    if request.method == 'POST':
        # 获取数据
        data = get_data()
        # 构造sql语句
        #   select * from 表1 left join 表2 on 表1的id = 表2的外键  where id = data['pid']
        sql1 = '''select * from section where id = %d '''%(int(data['pid']))
        res = db1.find(sql1)
        print(res)
        sum = int(res['sum'])+1
        sql2 = 'update section set sum = %d where id = %d '%(sum,int(data['pid']))
        db1.intsert(sql2)
        sql = """insert into staff values(0,"%s","%s","%d","%d")"""%(data['name'],data['gender'],int(data['salary']),int(data['pid']))
        # db添加
        db1.intsert(sql)
        # 返回结果
        return jsonify({'code':200})
    # 获取出所有的数据
    elif request.method == 'GET':
        data = request.form
        sql = """select * from staff"""
        res = db1.fingall(sql)
        return jsonify({'code':200,'sections':res})

    # elif request.method == 'PUT':
        # 获取出来数据
        # id = request.args.get('id')

    # 修改
    elif request.method == 'PUT':
                # 获取用户输入的数据
        data = request.data
        if  data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        # 构造sql语句  update 表名 set 字段名1=值,字段名2=值 where id=1
        sql = """update staff set name="%s",gender="%s",salary="%s",pid=%d where id=%d"""%(data['name'],data['gender'],data['salary'],int(data['pid']),int(data['id']))
        print(sql)
        db1.intsert(sql)
        return jsonify({'code':200})

    # 删除数据
    elif request.method == 'DELETE':
        id = request.args.get('id')
        sql = """delete from staff where id=%d"""%(int(id))
        db1.intsert(sql)
        return jsonify({'code':200})

# 导入myfile文件里面的myfile方法
from utils.myfile import myfile
# 创建文件接口
@bp_course.route('/upload',methods=['POST'])
def upload():
    # 获取文件
    file = request.files['file']
    # 选择文件夹
    # 创建文件夹   文件夹的名称
    myfile.file_mkdir(3)
    # 保存文件                    文件夹的路径
    file.save(os.path.join('./static/upload/3/',file.filename))
    # 保存 返回ok
    return 'ok'

# 景区类型操作
@bp_course.route('/spot',methods=['POST','GET','PUT','DELETE'])
def spot():
    # 添加景区类型
    if request.method == 'POST':
        # 获取数据
        data = get_data()
        # 如果获取出来了数据
        if data:
            # 构造sql语句
            sql = """insert into spot values(0,"%s")"""%(data['name'])
            # 添加
            db1.intsert(sql)
            return jsonify({'code':200})
    # 修改数据
    
    elif request.method == 'PUT':
        pass
    # 删除数据

    elif request.method == 'DELETE':
        pass
    
    # 获取数据
    else:
        # 查看所有数据
        sql = """select * from spot"""
        db1.fingall(sql)
        return jsonify({'code':200})


# 景点操作
@bp_course.route('/scenic',methods=['POST','GET','PUT','DELETE'])
def scenic():
    # 添加
    if request.method == 'POST':
        # 获取数据
        data = request.form
        # 如果获取出来了
        if data:
            # 构造sql语句
            sql = """insert into scenic values("%s",%.2f,%d)"""%(data['name'],float(data['price']),int(data['pid']))
            # 添加
            db1.intsert(sql)
            # 获取新加的id
            sql1 = """select id from scenic where name='%s'"""%(data['name'])
            res = db1.find(sql1)
            # 文件上传,上传成功后图片路径
            file = request.files['file']
            myfile.file_mkdir(str(['id']))
            file.save(os.path.join('./static/upload/'+str(res['id']),file.filename))                                                                                                                                                                                                                                                                                                                                         
            #组装数据添加
            sql3 = "update scenic set pic='%s' where id=%d"%('/static/upload/'+str(res['id'])+"/"+file.filename,int(res['id']))
            db1.intsert(sql3)
            return jsonify({"code":200})
        else:
            sql = 'select * from scenic'
            res = db1.fingall(sql)
            return jsonify({"code":200,'list':res})


    # 修改数据
    elif request.method == 'PUT':
        pass

    # 删除数据
    elif request.method == 'DELETE':
        pass

    # 获取数据
    else:
        sql = """select * from scenic"""
        db1.fingall(sql)
        return jsonify({'code':200})


#文件上传接口
@bp_course.route('/uploads',methods=['POST'])
def uploads():
    file = request.files['file']
    cityid = request.form['cityid']
    #创建文件夹
    myfile.file_mkdir(cityid)
    #图片上传
    file.save(os.path.join('./static/upload/'+str(cityid),file.filename))
    return jsonify({"code":200,'url':'/static/upload/'+str(cityid)+'/'+file.filename})

# 查询景区接口
@bp_course.route('/citym')
def citym():
    sql = "select id,name from city"
    res = db1.fingall(sql)
    return jsonify({"code":200,'list':res})

# 添加景区接口
@bp_course.route('/prom',methods=['POST','GET'])
def prom():
    if request.method == 'POST':
        data = get_data()
        sql = "insert into product(title,price,city_id,pic) values('%s',%.2f,%d,'%s')"%(data['title'],float(data['price']),int(data['city_id']),data['pic'])
        db1.intsert(sql)
        return jsonify({"code":200})

    else:
        #根据分类id查询分类下商品
        cityid = request.args.get('cityid')
        if  cityid == '0':
            sql = "select * from product"
        else:
            sql = "select * from product where city_id=%d"%(int(cityid))
        res = db1.fingall(sql)
        return jsonify({"code":200,'list':res})


# 获取分类接口
@bp_course.route('/cateM',methods=['POST','GET'])
def cateM():
    if request.method == 'GET':
        sql = """select * from yptype"""
        res = db1.fingall(sql)
        return jsonify({'code':200,'list':res})

#获取记录接口
import datetime
@bp_course.route('/recordM')
def recordM():
    #获取分类id
    id = request.args.get('typeid')
    if id == '0':
        sql = 'select * from record'
    else:
        sql = 'select * from record where typeid=%d'%(int(id))
    res = db1.fingall(sql)
    list=[]
    for i in res:
        dict={'id':i['id'],'stime':datetime.datetime.strftime(i['stime'],'%Y-%m-%d'),'etime':datetime.datetime.strftime(i['etime'],'%Y-%m-%d'),'money':float(i['money'])}
        list.append(dict)
    print(list)
    return jsonify({"code":200,'list':list})

#获取分类操作接口
@bp_course.route('/orderM',methods=['GET','PUT'])
def orderM():
    if request.method == "PUT":
        id = request.args.get('id')
        sql = "select * from orders where id=%d"%(int(id))
        res = db1.find(sql)
        #判断状态原来为1改成2，原来为2改成1
        status = 2
        if int(res['status']) == 2:
            status=1
        
        #执行更新操作
        sql1 = "update orders set status=%d where id=%d"%(status,int(id))
        db1.intsert(sql1)
        return jsonify({"code":200})

    else:
        #当前页
        page = int(request.args.get('page'))
        #每页显示多少条
        page_size = int(request.args.get('page_size'))
        start = (page-1)*page_size
        sql = 'select * from orders limit %d,%d'%(start,page_size)
        res = db1.fingall(sql)
        #总条数
        sql1 = "select count(id) from orders"
        res1 = db1.find(sql1)
        return jsonify({"code":200,'list':res,'total':res1['count(id)']})



# 订单商品的接口操作
@bp_course.route('/ordersM',methods=['POST','GET'])
def ordersM():
    if request.method == 'GET':
        sql = "select * from orders"
        res = db1.fingall(sql)
        return jsonify({'code':200,'list':res})

    elif request.method == 'POST':
        data = get_data()
        print(data)
        sql = """insert into order_detail(goods_name,count,price,order_id) values("%s",%d,%.2f,%d)"""%(data['goods_name'],int(data['count']),int(data['price']),int(data['order_id']))
        print(sql)
        db1.intsert(sql)
        return jsonify({'code':200})

# 发红包200-0.01区间接口
@bp_course.route('/redmoney')
def redmoney():
    # 接收到输入的金额
    money = request.args.get('money')
    # 如果没有收到金额
    if not money:
        # 返回结果必须输入金额
        return jsonify({'code':10011,'mes':'必须输入金额'})
    # 有金额
    else:
        # 如果有金额
        print(money)
        try:
            # 把金额转成float类型
            money = float(money)
        # 否则返回格式有误
        except:
            return jsonify({'code':10012,'mes':'格式有误'})
    # 如果输入的金额小于200大于0.01
    if money <200 and money > 0.01:
        # 返回200成功
        return jsonify({'code':200})
    # 否则
    else:
        # 返回20010错误
        return jsonify({'code':20010,'mes':'范围不符合'})

# 发红包页面接口
@bp_course.route('/sendMoney',methods=['POST'])
def sendMoney():
    # 获取数据
    data = get_data()
    # 添加数据
    sql = """insert into test_record(name,url,method,params,result) values("%s","%s","%s","%s","%s")"""%(data['name'],data['url'],data['method'],data['params'],data['result'])
    # 添加
    db1.intsert(sql)
    # 返回结果
    return jsonify({'code':200})

# 
import requests
@bp_course.route('/test_sendMoney')
def test_sendMoney():
    #读取数据库
    sql = "select * from test_record where status=1"
    res = db1.findall(sql)
    list=[]
    for i in res:
        flag = "失败"
        params = json.loads(i['params'])
        if i['method'] == "get":
            mes = requests.get(i['url'],params=params)
        elif i['method'] == "post":
            mes = requests.post(i['url'],data=params)
        mm = json.loads(mes.text)
        if mm['code'] == int(i['result']):
            flag='成功'
        str={"name":i['name'],"请求地址":i['url'],"返回信息":mes.text,"测试结果":flag}
        list.append(str)
        filename = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d')
        with open(os.path.join('./logs/'+filename+'.txt'),'w') as f:
            f.write(json.dumps(list,ensure_ascii=False))
    return jsonify({"code":200})


import re
import time,random
#发送验证码
@bp_course.route('/sendSms',methods=['POST'])
def sendSms():
    #获取手机号
    data = get_data()
    try:
         mobile = data['mobile']  
    except:
       return jsonify({"code":10011,'mes':'不能为空'})

    #验证手机号是否合法
    res = re.match('^1[3-9]\d{9}$',mobile)
    if not res:
        return jsonify({"code":10010,'mes':'手机号不合法'})
    #检查上次发送是否超过一分钟，1分钟内不能发
    sql = "select stime from trecord where mobile='%s' order by id desc limit 1"%(str(mobile))
    record = db1.find(sql)
    if record:
        #判断时间是否在一分钟以内
        seconds = int(time.time())-int(record['stime'])
        if seconds<60:
            return jsonify({"code":10012,"mes":'一分钟内不能重复发送'})
    #生成验证码，发送
    code = random.randint(100000,999999)
    #当发送成功写入记录表
    sql2 = "insert into trecord(mobile,code,stime) values('%s',%d,%d)"%(str(mobile),code,int(time.time()))
    db1.intsert(sql2)
    return jsonify({"code":200,'mes':'发送成功'})



# 登录接口
@bp_course.route('/tlogin',methods=['POST'])
def tlogin():
    # 获取手机验证码
    data = get_data()
    # 通过手机号去记录中表查询,查询最近一条
    sql = "select code,stime from trecord where mobile='%s' order by id desc limit 0,1"%(data['mobile'])
    res = db1.find(sql)
    # 验证码过期时间验证
    if int(time.time())-int(res['stime'])>60:
        return jsonify({'code':10020,'mes':'验证码过期,重新发送'})
    # 验证是否相同
    print(type(res['code']))
    print(type(data['code']))
    if int(res['code']) == int(data['code']):
        # 用户表中查询手机号是否存在
        sql1 = "select id from tuser where mobile='%s'"%(data['mobile'])
        user = db1.find(sql1)
        # 存在返回登录成功userid
        if user:
            return jsonify({'code':200,'userid':user['id'],'mes':'登录成功'})
        # 不存在添加新用户返回userid
        sql2 = "insert into tuser(mobile) values('%s')"%(data['mobile'])
        db1.intsert(sql2)
        sql3 = """select id from tuser where mobile='%s'"""%(data['mobile'])
        user3 = db1.find(sql3)
        return jsonify({'code':200,'uiserid':user3['id']})
    else:
        return jsonify({'code':10021,'mes':'验证码输入错误'})

# 搜索商品接口
@bp_course.route('/searchMs')
def search():
    #获取数据
    title = request.args.get('title')
    #判断是否为空去掉空格
    title = title.strip()
    if not title:
        return jsonify({"code":10030,'mes':'搜索内容不能为空'})
    #判断长度 5-10
    if 1<=len(title)<=10:
        #数据库查询
        sql = "select * from shop where title like '%"+title+"%'"
        print(sql)
        res = db1.fingall(sql)
        #写入记录表
        ip = request.remote_addr
        sql2 = "insert into browse(title,ip) values('%s','%s')"%(title,ip)
        #返回结果
        db1.intsert(sql2)
        return jsonify({"code":200,'list':res})
    else:
        return jsonify({"code":10031,'mes':'长度不合法'})

# 商品操作接口
@bp_course.route('/goodsM',methods=['POST'])
def goodsM():
    # 获取数据
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    

# 登录接口
@bp_course.route('/author_login',methods=['POST'])
def author_login():
    # 获取数据
    data = get_data()
    # 判断用户名和密码是否为空
    try:
        username = data['username']
        password = data['password']
    except:
        return jsonify({'code':20010,'mes':'必须输入用户名和密码'}) 
    if not all([username,password]):
        return jsonify({'code':20011,'mes':'必须输入用户名和密码'})
    # 根数用户名去数据库查找
    sql = """select * from author where username='%s'"""%(username)
    res = db1.find(sql)
    if res:
    # 查看到比较密码
        if res['password'] == password:
            # 比对成功返回id username
            return jsonify({"code":200,"mes":"登录成功","userid":res['id'],"username":res['username']})
        # 失败提示密码错误
        else:
            return jsonify({"code":20022,"mes":'密码错误'})
    # 没查到返回此用户不存在
    else:
        return jsonify({"code":20023,"mes":"用户名不存在"})


# 小说管理接口
@bp_course.route('/booksM',methods=['POST'])
def booksM():
    # 获取数据
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    # 对数据进行验证
    try:
        title = data['title']
        # 是否为空
        if not title:
            return jsonify({"code":10010,'mes':"必须输入标题"})
    except:
        return jsonify({"code":10011})
    # 验证是否重复
    ctime = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%m:%S')
    sql = "select id from books where title='%s'"%(title)
    res = db1.find(sql)
    if res:
        return jsonify({'code':10012,'mes':'标题不能重复'})
    else:
        sql = "insert into books(title,content,pic,author_id,ctime) values('%s','%s','%s','%d','%s')"%(data['title'],data['content'],data['pic'],int(data['author_id']),ctime)
        db1.intsert(sql)
    return jsonify({'code':200,})
